今天,我闲来没事,玩起了va_list
。
可是,我发现,MS
好像比较偏爱__crt_va_start
,就是不让va_start
好好显示。
于是,为了可变参数,我启动了template
。
使用template
可变参数的框架大致如下(我用我的myprint
举例):
xxxxxxxxxx
template <class type, class ...args>
void myprint(type a, args... arg) {
...
}
他有两个地方和普通函数不同:
参数数量可变
参数类型可变
我们的目标:
实现一个
myprint
函数,让函数可以输出任何东西
代码:
xxxxxxxxxx
using namespace std;
template <class type>
void myprint(type a) {
cout << a;
}
template <class type, class ...args>
void myprint(type a, args... arg) {
cout << a;
if (sizeof...(arg)) {
myprint(arg...);
}
}
int main() {
myprint("Hello world!", '\n', 114514);
return 0;
}
输出:
xxxxxxxxxx
Hello world!
114514
D:\Visual Studio 2022\C++\x64\Debug\C++.exe (进程 12620)已退出,代码为 0。
按任意键关闭此窗口. . .